package cn.bonoon.kernel.bytecode;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;

import cn.bonoon.kernel.events.OperateEvent;
import cn.bonoon.kernel.io.FileManager;
import cn.bonoon.kernel.support.entities.Persistable;

/**
 * <pre>
 * 实现值从普通的实体到数据库实体的转换；转换过程应该能够通过指定对某些特殊的值进行处理；
 * 如：自动生成编码、加密解密、提取关键词等
 * 
 * 往数据库实体写值，过程需要操作到数据库，所以需要把转值的操作在控制器层转到服务层来，
 * 这样才能使用相同的事务和进行同步控制
 * </pre>
 * @author jackson
 *
 */
public class EntityWriter {
	
	public Persistable writeUpdate(Object obj, OperateEvent event, EntityManager entityManager, Long id)throws Exception{
		throw new RuntimeException("不支持对数据库实体的更新操作！");
	}
	
	public Persistable writeUpdate(Object obj, OperateEvent event, EntityManager entityManager, Persistable entity)throws Exception{
		throw new RuntimeException("不支持对数据库实体的更新操作！");
	}
	
	public Persistable writeInsert(Object obj, OperateEvent event, EntityManager entityManager)throws Exception{
		throw new RuntimeException("不支持对数据库实体的添加操作！");
	}
	
	public Persistable writeInsert(Object obj, OperateEvent event, EntityManager entityManager, Persistable entity)throws Exception{
		throw new RuntimeException("不支持对数据库实体的添加操作！");
	}
	
	//在很多情况下是不需要上传文件的
	private Map<String, FileManager> fileManagers;
	protected FileManager getFileManager(OperateEvent event, String fileManagerName){
		FileManager fileManager;
		if(null == fileManagers){
			fileManagers = new HashMap<>();
			fileManager = event.getApplicationContext().getBean(fileManagerName, FileManager.class);
			fileManagers.put(fileManagerName, fileManager);
		}else{
			fileManager = fileManagers.get(fileManagerName);
			if(null == fileManager){
				fileManager = event.getApplicationContext().getBean(fileManagerName, FileManager.class);
				fileManagers.put(fileManagerName, fileManager);
			}
		}
		return fileManager;
	}
}
